/* 
 * File:   i2c_hal.c
 * Author: apleilx
 *
 * 
 */

#include "i2c_hal.h"

/*****************************************************************************//*!
   *
   * @brief send out start signals.
   *        
   * @param[in] pI2Cx      point to I2C module type.
   *
   * @return error status
   *
   * @ Pass/ Fail criteria: none
*****************************************************************************/
uint8_t I2C_Start(I2C_TypeDef *pI2Cx)
{
    uint32_t u32Timeout;
    uint8_t u8ErrorStatus;
    
    u32Timeout = 0; 
    u8ErrorStatus = 0x00;
    
    /* Enable I2C_CTLR1_GENSTA control bit */
    pI2Cx->CTLR1 |= I2C_CTLR1_GENSTA;

    while( (!(pI2Cx->STR1 & I2C_STR1_SBSEND)) && ( u32Timeout < I2C_WAIT_STATUS_TIMEOUT))
     {
        u32Timeout ++;
     }

     if( u32Timeout == I2C_WAIT_STATUS_TIMEOUT )
     {
        u8ErrorStatus |= I2C_ERROR_BUS_BUSY;
     }

     return u8ErrorStatus;
}

/*****************************************************************************//*!
   *
   * @brief send out stop signals.
   *        
   * @param[in] pI2Cx      point to I2C module type.
   *
   * @return error status
   *
   * @ Pass/ Fail criteria: none
*****************************************************************************/
uint8_t I2C_Stop(I2C_TypeDef *pI2Cx)
{
    uint32_t u32Timeout;
    uint8_t u8ErrorStatus;
    
    u32Timeout = 0; 
    u8ErrorStatus = 0x00;

    // Enable I2C_CTLR1_GENSTP control bit
    pI2Cx->CTLR1 |= I2C_CTLR1_GENSTP;

    while( (!(pI2Cx->CTLR1 & I2C_CTLR1_GENSTP)) && ( u32Timeout < I2C_WAIT_STATUS_TIMEOUT))
     {
        u32Timeout ++;
     }

     if( u32Timeout == I2C_WAIT_STATUS_TIMEOUT )
     {
        u8ErrorStatus |= I2C_ERROR_BUS_BUSY;
     }

     return u8ErrorStatus;
}


/*****************************************************************************//*!
   *
   * @brief send a byte.
   *        
   * @param[in] pI2Cx      point to I2C module type.
   *
   * @return error status
   *
   * @ Pass/ Fail criteria: none
*****************************************************************************/
uint8_t I2C_MasterSendByte(I2C_TypeDef *pI2C,uint8_t Data)
{
    uint32_t TimeoutCnt;	
	
	pI2C->STR1 &= ~I2C_STR1_AE;
	
	I2C_SendData(pI2C, Data);
	TimeoutCnt = 0;
	while(!I2C_StateDetect(pI2C, I2C_PROGRAMMINGMODE_MASTER_BYTE_TRANSMITTED)
		&& (TimeoutCnt < I2C_WAIT_STATUS_TIMEOUT))
	{
		TimeoutCnt++;
	}
	if(TimeoutCnt == I2C_WAIT_STATUS_TIMEOUT)
	{
		return I2C_ERROR_NO_WAIT_TCF_FLAG;
	}
	// Ack check
	if(pI2C->STR1 & I2C_STR1_AE)
	{
		pI2C->STR1 &= ~I2C_STR1_AE;
		return I2C_ERROR_NO_GET_ACK;
	}	
	
	return I2C_ERROR_NULL;
}
